package com.loongtech.bi.action.system;

import com.loongtech.bi.entity.system.EntityMonitorConfig;
import com.loongtech.bi.entity.system.EntityMonitorGroupConfig;
import com.loongtech.bi.manager.system.BiMonitorConfigManager;
import com.loongtech.bi.manager.system.BiMonitorGroupConfigManager;
import com.loongtech.core.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Scope("view")
public class BiMonitorConfigAction {
	@Resource
	private BiMonitorConfigManager biMonitorConfigManager;
	@Resource
	private BiMonitorGroupConfigManager groupManager;

	private EntityMonitorConfig monitorConfigEntity;
	private List<EntityMonitorConfig> monitorConfigEntityList;
	private Map<Integer, EntityMonitorGroupConfig> groupMap = new HashMap<>();

	@Autowired
	private void inital() {
		for (EntityMonitorGroupConfig group : groupManager.findAll()) {
			groupMap.put(group.getId(), group);
		}
		monitorConfigEntityList = biMonitorConfigManager.queryList();
		monitorConfigEntity = new EntityMonitorConfig();
//        initalSQL();
	}

/*    private void initalSQL() {
        List<EntityMonitorConfig> list = biMonitorConfigManager.findByQuery("from EntityMonitorConfig order by id");
            for (EntityMonitorConfig vo : list) {
                String str = vo.getInquerySQL();
                String desc = vo.getDescription();
                int index = str.lastIndexOf(">");

                String th = str.substring(index + 1);
                String sql = str.substring(0,str.lastIndexOf(">") + 1) + "@thresh";
                desc = desc.substring(0,desc.lastIndexOf("于") + 1) + "@thresh";

                System.out.println(th);
                System.out.println(sql);
                System.out.println(desc);

                vo.setThreshHold(Long.parseLong(th));
                vo.setInquerySQL(sql);
                vo.setDescription(desc);

                biMonitorConfigManager.merge(vo);

            }
    }

    public static void main(String[] args) {
        String s = "select serverid,roleid,sum(changenum) getnum from realtime_item where dt='@date' and itemid='4584' and changenum>0 and reason<>11 group by serverid, roleid having getnum>5";
        String str = s;
        String desc = "aaaa大于8";
        int index = str.lastIndexOf(">");

        String th = str.substring(index + 1);
        String sql = str.substring(0,str.lastIndexOf(">") + 1) + "@thresh";
        desc = desc.substring(0,desc.lastIndexOf("于") + 1) + "@thresh";


        System.out.println(th);
        System.out.println(sql);
        System.out.println(desc);
    }*/
    private Map<String, String> status2str = new HashMap<String, String>() {
        private static final long serialVersionUID = 1L;

		{
			put("NONE", "完成");
			put("NORMAL", "正常");
			put("PAUSED", "暂停");
			put("COMPLETE", "完成");
			put("ERROR", "错误");
			put("BLOCKED", "阻塞");
		}
	};

	public String getStatusStr(String status) {
		return StringUtils.isEmpty(status2str.get(status)) ? status : status2str.get(status);
	}

	public void searchByCriteria() {
		monitorConfigEntityList = biMonitorConfigManager.searchByCriteria(monitorConfigEntity);
	}

	/**
	 * 开始任务
	 */
	public void addEntityMonitorConfig() throws Exception{
		FacesContext faceContext = FacesContext.getCurrentInstance();
		if (validate(faceContext, monitorConfigEntity)) {
			biMonitorConfigManager.addEntityMonitorConfig(monitorConfigEntity.getStartTime().getTime(), monitorConfigEntity.getEndTime().getTime(), monitorConfigEntity);
			faceContext.addMessage(null, new FacesMessage("提示", "添加成功！"));
			inital();
		}
	}

    /**
     * 全部开始
     */
    public void startAllEntityMonitorConfig() throws Exception{
        FacesContext faceContext = FacesContext.getCurrentInstance();
        biMonitorConfigManager.startAllEntityMonitorConfig();
        faceContext.addMessage(null, new FacesMessage("提示", "全部开始成功！"));
        inital();
    }

	/**
	 * 废除
	 */
	public void delEntityMonitorConfig(String id) throws Exception{
		FacesContext faceContext = FacesContext.getCurrentInstance();
		biMonitorConfigManager.delEntityMonitorConfig(id);
		faceContext.addMessage(null, new FacesMessage("提示", "废除成功！"));
		inital();
	}

    /**
     * 全部暂停
     */
    public void pauseAllEntityMonitorConfig() throws Exception{
        FacesContext faceContext = FacesContext.getCurrentInstance();
        biMonitorConfigManager.pauseAllEntityMonitorConfig();
        faceContext.addMessage(null, new FacesMessage("提示", "全部暂停成功！"));
        inital();
    }

    /**
     * 全部恢复
     */
    public void resumeAllEntityMonitorConfig() throws Exception{
        FacesContext faceContext = FacesContext.getCurrentInstance();
        biMonitorConfigManager.resumeAllEntityMonitorConfig();
        faceContext.addMessage(null, new FacesMessage("提示", "全部恢复成功！"));
        inital();
    }

	/**
	 * 暂停
	 */
	public void pauseScheduleJob(String scheduleJobId) throws Exception{
		FacesContext faceContext = FacesContext.getCurrentInstance();
		biMonitorConfigManager.pauseMonitor(scheduleJobId);
		faceContext.addMessage(null, new FacesMessage("提示", "暂停成功！"));
		inital();
	}

	/**
	 * 恢复
	 */
	public void resumeScheduleJob(EntityMonitorConfig e) throws Exception{
		FacesContext faceContext = FacesContext.getCurrentInstance();
		biMonitorConfigManager.resumeMonitor(e.getStartTime().getTime(), e.getEndTime().getTime(),e);
		faceContext.addMessage(null, new FacesMessage("提示", "恢复成功！"));
		inital();
	}

	/**
	 * 修改
	 */
	public void modifyEntityMonitorConfig(EntityMonitorConfig e) throws Exception{
		FacesContext faceContext = FacesContext.getCurrentInstance();
		if (validate(faceContext, e)) {
			biMonitorConfigManager.modifyEntityMonitorConfig(e.getStartTime().getTime(), e.getEndTime().getTime(),e);
			faceContext.addMessage(null, new FacesMessage("提示", "修改成功！"));
			inital();
		}
	}

	private boolean validate(FacesContext faceContext, EntityMonitorConfig emc) {

		if (null != emc.getCountNum()) {
			if (emc.getCountNum() <= 0) {
				faceContext.addMessage(null, new FacesMessage("提示", "监控次数需大于0！"));
				return false;
			} else if (emc.getCountNum() > Integer.MAX_VALUE) {
				emc.setCountNum(Integer.MAX_VALUE);
			}

		}
		if (null == emc.getGroupId() || emc.getGroupId() < 0) {
			faceContext.addMessage(null, new FacesMessage("提示", "监控组别不能为空！"));
			return false;
		}

        if (null == emc.getThreshHold()) {
            faceContext.addMessage(null, new FacesMessage("提示", "监控阀值不能为空！"));
            return false;
        }

		if (null == emc.getIntervalTime() || emc.getIntervalTime() <= 0) {
			faceContext.addMessage(null, new FacesMessage("提示", "监控频率不合法！"));
			return false;
		}
		if (Utils.isEmptyStr(emc.getInquerySQL())) {
			faceContext.addMessage(null, new FacesMessage("提示", "查询语句不能为空！"));
			return false;
		}
		if (emc.getStartTime() == null) {
			faceContext.addMessage(null, new FacesMessage("提示", "开始时间不能为空！"));
			return false;
		}
		if (emc.getEndTime() == null) {
			faceContext.addMessage(null, new FacesMessage("提示", "结束时间不能为空！"));
			return false;
		}
		if (emc.getIntervalTime() == null) {
			faceContext.addMessage(null, new FacesMessage("提示", "监控频率不能为空！"));
			return false;
		}
		if (emc.getEndTime().getTime() < emc.getStartTime().getTime()) {
			faceContext.addMessage(null, new FacesMessage("提示", "结束时间需大于开始时间！"));
			return false;
		}

		return true;
	}

	public EntityMonitorConfig getMonitorConfigEntity() {
		return monitorConfigEntity;
	}

	public void setMonitorConfigEntity(EntityMonitorConfig monitorConfigEntity) {
		this.monitorConfigEntity = monitorConfigEntity;
	}

	public List<EntityMonitorConfig> getMonitorConfigEntityList() {
		return monitorConfigEntityList;
	}

	public void setMonitorConfigEntityList(List<EntityMonitorConfig> monitorConfigEntityList) {
		this.monitorConfigEntityList = monitorConfigEntityList;
	}

	public Map<Integer, EntityMonitorGroupConfig> getGroupMap() {
		return groupMap;
	}

	public void setGroupMap(Map<Integer, EntityMonitorGroupConfig> groupMap) {
		this.groupMap = groupMap;
	}
}
